import React, { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { Plus, Edit, Trash2, Star, X, Lock } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useAuth } from '@/contexts/AuthContext';

interface AiModel {
  id: number;
  name: string;
  model_id: string;
  model_type: string;
  api_endpoint: string;
  api_key: string;
  is_default: boolean;
  is_enabled: boolean;
  max_tokens?: number;
  temperature?: number;
  description?: string;
  created_at?: string;
  updated_at?: string;
}

interface ModelFormData {
  name: string;
  model_id: string;
  model_type: string;
  api_endpoint: string;
  api_key: string;
  is_default: boolean;
  max_tokens: string;
  temperature: string;
  description: string;
}

const MODEL_TYPES = [
  { value: 'openai', label: 'OpenAI' },
  { value: 'claude', label: 'Claude (Anthropic)' },
  { value: 'gemini', label: 'Google Gemini' },
  { value: 'openrouter', label: 'OpenRouter' },
  { value: 'local', label: '本地模型' },
  { value: 'other', label: '其他' },
];

// OpenRouter常用模型预设
const OPENROUTER_PRESETS = [
  {
    name: 'GPT-4 Turbo (OpenRouter)',
    model_id: 'openai/gpt-4-turbo',
    api_endpoint: 'https://openrouter.ai/api/v1/chat/completions',
    max_tokens: 4096,
    temperature: 0.7,
    description: 'OpenAI GPT-4 Turbo via OpenRouter',
  },
  {
    name: 'Claude 3.5 Sonnet (OpenRouter)',
    model_id: 'anthropic/claude-3.5-sonnet',
    api_endpoint: 'https://openrouter.ai/api/v1/chat/completions',
    max_tokens: 4096,
    temperature: 0.7,
    description: 'Anthropic Claude 3.5 Sonnet via OpenRouter',
  },
  {
    name: 'Claude 3 Opus (OpenRouter)',
    model_id: 'anthropic/claude-3-opus',
    api_endpoint: 'https://openrouter.ai/api/v1/chat/completions',
    max_tokens: 4096,
    temperature: 0.7,
    description: 'Anthropic Claude 3 Opus via OpenRouter',
  },
  {
    name: 'Gemini Pro 1.5 (OpenRouter)',
    model_id: 'google/gemini-pro-1.5',
    api_endpoint: 'https://openrouter.ai/api/v1/chat/completions',
    max_tokens: 8192,
    temperature: 0.7,
    description: 'Google Gemini Pro 1.5 via OpenRouter',
  },
  {
    name: 'Meta Llama 3.1 405B (OpenRouter)',
    model_id: 'meta-llama/llama-3.1-405b-instruct',
    api_endpoint: 'https://openrouter.ai/api/v1/chat/completions',
    max_tokens: 4096,
    temperature: 0.7,
    description: 'Meta Llama 3.1 405B via OpenRouter',
  },
];

export default function ModelManagement() {
  const { isAuthenticated } = useAuth();
  const [models, setModels] = useState<AiModel[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [formData, setFormData] = useState<ModelFormData>({
    name: '',
    model_id: '',
    model_type: 'openai',
    api_endpoint: '',
    api_key: '',
    is_default: false,
    max_tokens: '4096',
    temperature: '0.7',
    description: '',
  });
  const [showPresets, setShowPresets] = useState(false);

  useEffect(() => {
    if (isAuthenticated) {
      loadModels();
    }
  }, [isAuthenticated]);

  const loadModels = async () => {
    try {
      setLoading(true);
      const result = await invoke<AiModel[]>('get_ai_models');
      setModels(result);
    } catch (error) {
      console.error('Failed to load models:', error);
      alert('加载模型失败: ' + error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      const payload = {
        name: formData.name,
        modelId: formData.model_id,
        modelType: formData.model_type,
        apiEndpoint: formData.api_endpoint,
        apiKey: formData.api_key,
        isDefault: formData.is_default,
        maxTokens: formData.max_tokens ? parseInt(formData.max_tokens) : null,
        temperature: formData.temperature ? parseFloat(formData.temperature) : null,
        description: formData.description || null,
      };

      if (editingId) {
        await invoke('update_ai_model', {
          id: editingId,
          ...payload,
        });
      } else {
        await invoke('create_ai_model', payload);
      }

      await loadModels();
      resetForm();
    } catch (error) {
      console.error('Failed to save model:', error);
      alert('保存失败: ' + error);
    }
  };

  const handleEdit = (model: AiModel) => {
    setEditingId(model.id);
    setFormData({
      name: model.name,
      model_id: model.model_id,
      model_type: model.model_type,
      api_endpoint: model.api_endpoint,
      api_key: model.api_key,
      is_default: model.is_default,
      max_tokens: model.max_tokens?.toString() || '4096',
      temperature: model.temperature?.toString() || '0.7',
      description: model.description || '',
    });
    setShowForm(true);
  };

  const handleDelete = async (id: number) => {
    if (!confirm('确定要删除这个模型吗？')) return;

    try {
      await invoke('delete_ai_model', { id });
      await loadModels();
    } catch (error) {
      console.error('Failed to delete model:', error);
      alert('删除失败: ' + error);
    }
  };

  const handleSetDefault = async (id: number) => {
    try {
      await invoke('set_default_ai_model', { id });
      await loadModels();
    } catch (error) {
      console.error('Failed to set default model:', error);
      alert('设置默认模型失败: ' + error);
    }
  };

  const resetForm = () => {
    setShowForm(false);
    setEditingId(null);
    setShowPresets(false);
    setFormData({
      name: '',
      model_id: '',
      model_type: 'openai',
      api_endpoint: '',
      api_key: '',
      is_default: false,
      max_tokens: '4096',
      temperature: '0.7',
      description: '',
    });
  };

  const applyPreset = (preset: typeof OPENROUTER_PRESETS[0]) => {
    setFormData({
      ...formData,
      name: preset.name,
      model_id: preset.model_id,
      api_endpoint: preset.api_endpoint,
      max_tokens: preset.max_tokens.toString(),
      temperature: preset.temperature.toString(),
      description: preset.description,
    });
    setShowPresets(false);
  };

  const getModelTypeLabel = (type: string) => {
    return MODEL_TYPES.find(t => t.value === type)?.label || type;
  };

  // Show password prompt if needed
  if (!isAuthenticated) {
    return (
      <div className="flex flex-col items-center justify-center h-full">
        <Lock className="w-16 h-16 text-muted-foreground mb-4" />
        <h2 className="text-xl font-semibold mb-2">需要认证</h2>
        <p className="text-muted-foreground">请先登录密码管理器</p>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="flex justify-between items-center mb-6">
        <div>
          <h2 className="text-2xl font-bold text-foreground">AI 模型管理</h2>
          <p className="text-sm text-muted-foreground mt-1">
            配置和管理您的 AI 模型
          </p>
        </div>
        <Button
          onClick={() => setShowForm(true)}
          className="gap-2"
        >
          <Plus className="w-4 h-4" />
          添加模型
        </Button>
      </div>

      {/* Model Form Modal */}
      <AnimatePresence>
        {showForm && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
            onClick={resetForm}
          >
            <motion.div
              initial={{ scale: 0.95, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.95, opacity: 0 }}
              onClick={(e) => e.stopPropagation()}
              className="bg-card border border-border rounded-lg w-full max-w-3xl max-h-[90vh] overflow-hidden flex flex-col"
            >
              {/* Modal Header */}
              <div className="flex justify-between items-center p-6 border-b border-border">
                <h3 className="text-lg font-semibold">
                  {editingId ? '编辑模型' : '添加新模型'}
                </h3>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={resetForm}
                >
                  <X className="w-4 h-4" />
                </Button>
              </div>

              {/* Modal Body - Scrollable */}
              <div className="flex-1 overflow-y-auto p-6">

            <form id="model-form" onSubmit={handleSubmit} className="space-y-4">
              {/* OpenRouter预设按钮 */}
              {formData.model_type === 'openrouter' && !editingId && (
                <div className="mb-4">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => setShowPresets(!showPresets)}
                    className="w-full"
                  >
                    {showPresets ? '隐藏预设' : '使用OpenRouter预设模型'}
                  </Button>
                  
                  {showPresets && (
                    <div className="mt-2 p-3 border border-border rounded-md bg-muted/50 space-y-2">
                      <p className="text-sm text-muted-foreground mb-2">
                        选择一个预设模型快速配置：
                      </p>
                      {OPENROUTER_PRESETS.map((preset, index) => (
                        <button
                          key={index}
                          type="button"
                          onClick={() => applyPreset(preset)}
                          className="w-full text-left px-3 py-2 text-sm rounded-md hover:bg-background border border-transparent hover:border-border transition-colors"
                        >
                          <div className="font-medium">{preset.name}</div>
                          <div className="text-xs text-muted-foreground">{preset.model_id}</div>
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              )}

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="name">模型名称 *</Label>
                  <Input
                    id="name"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    placeholder="例如: GPT-4"
                    required
                  />
                </div>
                <div>
                  <Label htmlFor="model_id">模型ID *</Label>
                  <Input
                    id="model_id"
                    value={formData.model_id}
                    onChange={(e) => setFormData({ ...formData, model_id: e.target.value })}
                    placeholder={formData.model_type === 'openrouter' ? '例如: openai/gpt-4-turbo' : '例如: gpt-4'}
                    required
                  />
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="model_type">模型类型 *</Label>
                  <select
                    id="model_type"
                    value={formData.model_type}
                    onChange={(e) => setFormData({ ...formData, model_type: e.target.value })}
                    className="w-full px-3 py-2 border border-input rounded-md bg-background"
                    required
                  >
                    {MODEL_TYPES.map(type => (
                      <option key={type.value} value={type.value}>
                        {type.label}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <Label htmlFor="api_endpoint">API 端点 *</Label>
                  <Input
                    id="api_endpoint"
                    value={formData.api_endpoint}
                    onChange={(e) => setFormData({ ...formData, api_endpoint: e.target.value })}
                    placeholder={
                      formData.model_type === 'openrouter' 
                        ? 'https://openrouter.ai/api/v1/chat/completions'
                        : 'https://api.openai.com/v1/chat/completions'
                    }
                    required
                  />
                  {formData.model_type === 'openrouter' && (
                    <p className="text-xs text-muted-foreground mt-1">
                      OpenRouter统一端点，通过model_id区分不同模型
                    </p>
                  )}
                </div>
              </div>

              <div>
                <Label htmlFor="api_key">API 密钥 *</Label>
                <Input
                  id="api_key"
                  type="password"
                  value={formData.api_key}
                  onChange={(e) => setFormData({ ...formData, api_key: e.target.value })}
                  placeholder={
                    formData.model_type === 'openrouter'
                      ? 'sk-or-v1-...'
                      : 'sk-...'
                  }
                  required
                />
                {formData.model_type === 'openrouter' && (
                  <p className="text-xs text-muted-foreground mt-1">
                    从 <a href="https://openrouter.ai/keys" target="_blank" rel="noopener noreferrer" className="underline">openrouter.ai/keys</a> 获取
                  </p>
                )}
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="max_tokens">最大令牌数</Label>
                  <Input
                    id="max_tokens"
                    type="number"
                    value={formData.max_tokens}
                    onChange={(e) => setFormData({ ...formData, max_tokens: e.target.value })}
                    placeholder="4096"
                  />
                </div>
                <div>
                  <Label htmlFor="temperature">Temperature</Label>
                  <Input
                    id="temperature"
                    type="number"
                    step="0.1"
                    min="0"
                    max="2"
                    value={formData.temperature}
                    onChange={(e) => setFormData({ ...formData, temperature: e.target.value })}
                    placeholder="0.7"
                  />
                </div>
              </div>

              <div>
                <Label htmlFor="description">描述</Label>
                <textarea
                  id="description"
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  placeholder="模型描述..."
                  className="w-full px-3 py-2 border border-input rounded-md bg-background min-h-[80px]"
                />
              </div>

              {/* API端点验证提示 */}
              {formData.api_endpoint && (
                <div className="p-3 border border-border rounded-md bg-muted/50">
                  <p className="text-sm font-medium mb-2">⚠️ 重要提示：</p>
                  <ul className="text-xs text-muted-foreground space-y-1">
                    <li>• OpenAI端点应为: <code className="bg-background px-1 py-0.5 rounded">https://api.openai.com/v1/chat/completions</code></li>
                    <li>• OpenRouter端点应为: <code className="bg-background px-1 py-0.5 rounded">https://openrouter.ai/api/v1/chat/completions</code></li>
                    <li>• Claude端点应为: <code className="bg-background px-1 py-0.5 rounded">https://api.anthropic.com/v1/messages</code></li>
                    <li>• 确保端点URL完整，包含 <code className="bg-background px-1 py-0.5 rounded">/chat/completions</code> 或对应路径</li>
                  </ul>
                </div>
              )}

              <div className="flex items-center gap-2">
                <input
                  type="checkbox"
                  id="is_default"
                  checked={formData.is_default}
                  onChange={(e) => setFormData({ ...formData, is_default: e.target.checked })}
                  className="w-4 h-4"
                />
                <Label htmlFor="is_default" className="cursor-pointer">
                  设为默认模型
                </Label>
              </div>

              </form>
              </div>

              {/* Modal Footer */}
              <div className="p-6 border-t border-border bg-muted/30">
                <div className="flex gap-2 justify-end">
                  <Button
                    type="button"
                    variant="outline"
                    onClick={resetForm}
                  >
                    取消
                  </Button>
                  <Button 
                    type="submit"
                    form="model-form"
                  >
                    {editingId ? '更新' : '创建'}
                  </Button>
                </div>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Models List */}
      <div className="flex-1 overflow-auto">
        {loading ? (
          <div className="flex justify-center items-center h-32">
            <div className="text-muted-foreground">加载中...</div>
          </div>
        ) : models.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-32 text-muted-foreground">
            <p>暂无模型</p>
            <p className="text-sm">点击"添加模型"开始配置</p>
          </div>
        ) : (
          <div className="grid gap-4">
            {models.map((model) => (
              <motion.div
                key={model.id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                className="bg-card border border-border rounded-lg p-4 hover:shadow-md transition-shadow"
              >
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-2">
                      <h3 className="text-lg font-semibold">{model.name}</h3>
                      {model.is_default && (
                        <span className="flex items-center gap-1 px-2 py-1 bg-primary/10 text-primary text-xs rounded-full">
                          <Star className="w-3 h-3 fill-current" />
                          默认
                        </span>
                      )}
                      <span className="px-2 py-1 bg-secondary text-secondary-foreground text-xs rounded-full">
                        {getModelTypeLabel(model.model_type)}
                      </span>
                    </div>
                    <div className="text-sm text-muted-foreground space-y-1">
                      <p><strong>模型ID:</strong> {model.model_id}</p>
                      <p><strong>API端点:</strong> {model.api_endpoint}</p>
                      {model.description && <p><strong>描述:</strong> {model.description}</p>}
                      {model.max_tokens && <p><strong>最大令牌:</strong> {model.max_tokens}</p>}
                      {model.temperature !== undefined && <p><strong>Temperature:</strong> {model.temperature}</p>}
                    </div>
                  </div>
                  <div className="flex gap-2">
                    {!model.is_default && (
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleSetDefault(model.id)}
                        title="设为默认"
                      >
                        <Star className="w-4 h-4" />
                      </Button>
                    )}
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleEdit(model)}
                    >
                      <Edit className="w-4 h-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleDelete(model.id)}
                      className="text-destructive hover:text-destructive"
                    >
                      <Trash2 className="w-4 h-4" />
                    </Button>
                  </div>
                </div>
              </motion.div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
